package com.wgke.bluetooth.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.media.Image;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.wgke.bluetooth.R;
import com.wgke.bluetooth.utils.LogUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.view.PressureRenderer;
import com.wgke.bluetooth.vm.BaseVM;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class PressureVisualizationActivity extends Activity {
    private GLSurfaceView glSurfaceView;
    private PressureRenderer renderer;
    private static final String TAG = "PressureVisualizationActivity";
    float strenth = 0.1f;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);
        glSurfaceView = findViewById(R.id.glSurfaceView);
        glSurfaceView.setEGLContextClientVersion(2);
        // 创建渲染器
        renderer = new PressureRenderer();
        glSurfaceView.setRenderer(renderer);
        // 设置渲染模式为按需渲染，提高性能
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
        findViewById(R.id.toggleViewButton).setOnClickListener(v -> {
            if (strenth == 1.0f) {
                strenth = 0.1f;
            } else {
                strenth = 1f;
                //startAnimation();
            }
            renderer.set3DEffectStrength(strenth);
        });

        findViewById(R.id.toggleViewButton2).setOnClickListener(v -> {
            ToastUtil.showMsg("显示图片");
            findViewById(R.id.imageView).setVisibility(View.VISIBLE);
            saveCurrentFrame(glSurfaceView, v.getContext());
        });

        BaseVM vm = new BaseVM();
        vm.createBtn(findViewById(R.id.layout_total1), "角度：", 1.0f, 0.1f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "角度：" + value);
            renderer.m3DEffectStrength = value;
        });

        vm.createBtn(findViewById(R.id.layout_total2), "视野：", 50.0f, 2f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "视野：" + value);
            renderer.FOV_3D = value;
        });

        vm.createBtn(findViewById(R.id.layout_total3), "近平面：", 0.5f, 0.1f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "视野：" + value);
            renderer.FOV_3D = value;
        });
        vm.createBtn(findViewById(R.id.layout_total3), "相机：",  2.5f, 0.1f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "相机：" + value);
            renderer.CAMERA_Z = value;
        });
        vm.createBtn(findViewById(R.id.layout_total4), "PLANE：",  20.0f, 1f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "PLANE：" + value);
            renderer.FAR_PLANE = value;
        });
        vm.createBtn(findViewById(R.id.layout_total5), "增高：",  0.6f, 0.1f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "增高：" + value);
            renderer.MAX_HEIGHT_SCALE = value;
        });
        vm.createBtn(findViewById(R.id.layout_total6), "着色点：",  5.0f, 0.5f, v -> {
            float value = (Float) v.getTag();
            LogUtil.d(TAG, "着色点：" + value);
          renderer.mPointSize = value;//0.05-0.3
            //renderer.setQuadSize(value);
        });

    }

    private void startAnimation() {
        new Thread(() -> {
            int count = 0;
            while (true) {
                count++;
                try {
                    Thread.sleep(50L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PointF point = new PointF(50f, 33f); // 圆心 (50, 33)
                float radius = 15f; // 半径15单位
                float angleDegrees = count * 1f; // 角度5度
                PointF pointOnCircle = getPointOnCircle(point, radius, angleDegrees);

              //runOnUiThread(() -> renderer.initTestData((int) pointOnCircle.x, (int) pointOnCircle.y));
                if (count > 500) {
                    return;
                }
            }
        }).start();
    }

    public PointF getPointOnCircle(PointF center, float radius, float angleDegrees) {
        float angleRadians = (float) Math.toRadians(angleDegrees);
        float x = center.x + radius * (float) Math.cos(angleRadians);
        float y = center.y + radius * (float) Math.sin(angleRadians);
        return new PointF(x, y);
    }

    @Override
    protected void onPause() {
        super.onPause();
        glSurfaceView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        glSurfaceView.onResume();
    }

    // 在PressureRenderer类中添加
    public void saveCurrentFrame(GLSurfaceView surfaceView, Context context) {
        surfaceView.queueEvent(() -> {
            try {
                // 获取Viewport尺寸
                int[] viewport = new int[4];
                GLES20.glGetIntegerv(GLES20.GL_VIEWPORT, viewport, 0);
                int width = viewport[2];
                int height = viewport[3];

                // 读取像素
                ByteBuffer buffer = ByteBuffer.allocateDirect(width * height * 4);
                buffer.order(ByteOrder.nativeOrder());
                GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);

                // 在主线程处理Bitmap
                new Handler(Looper.getMainLooper()).post(() -> {
                    try {
                        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                        buffer.rewind();
                        bitmap.copyPixelsFromBuffer(buffer);

                        // 翻转图像
                        Matrix matrix = new Matrix();
                        matrix.postScale(1, -1);
                        Bitmap flipped = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        ImageView iv = findViewById(R.id.imageView);
                        iv.setImageBitmap(flipped);
                        // 保存到文件
//                        File dir = new File(Environment.getExternalStoragePublicDirectory(
//                                Environment.DIRECTORY_PICTURES), "PressureMaps");
//                        if (!dir.exists()) dir.mkdirs();
//
//                        File file = new File(dir, "pressure_" +
//                                new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
//                                        .format(new Date()) + ".png");
//
//                        try (FileOutputStream out = new FileOutputStream(file)) {
//                            flipped.compress(Bitmap.CompressFormat.PNG, 100, out);
//                            Toast.makeText(context,
//                                    "Image saved to: " + file.getAbsolutePath(),
//                                    Toast.LENGTH_SHORT).show();
//                        }
                    } catch (Exception e) {
                        Log.e("PressureRenderer", "Bitmap creation failed", e);
                    }
                });
            } catch (Exception e) {
                Log.e("PressureRenderer", "Failed to read pixels", e);
            }
        });
    }
}